<?php
declare(strict_types=1);

namespace App\Service;

use App\Model\PermissionModel;
use Hyperf\Di\Annotation\Inject;
use function PHPUnit\Framework\isEmpty;
use function PHPUnit\Framework\isNull;

class PermissionService extends BaseService
{
	public function queryById($id)
	{
		if (!$id) {
			return null;
		}

		return PermissionModel::query()->findOrFail($id);
	}

	public function queryParents($exceptId = 0)
	{
		return PermissionModel::query()
			->where('id', '<>', $exceptId)
			->where('type', '<>', 3)->get([
			'id',
			'name',
		]);
	}

	public function store($insertData)
	{
		switch ($insertData['type']) {
			case 0: // 目录
				$insertData['request_uri'] = null;
				$insertData['request_method'] = null;
				break;
			case 1: // 菜单
				$insertData['request_method'] = 'GET';
				break;
			case 2: // 按钮
				$insertData['request_uri'] = null;
				$insertData['request_method'] = null;
				$insertData['menu_icon'] = null;
				break;
			case 3: // 接口
				$insertData['menu_icon'] = null;
				break;
			default:
				break;
		}
		$res = PermissionModel::create($insertData);
		if ($res) {
			return [
				'state' => 'success',
				'msg' => '操作成功',
			];
		}

		return [
			'state' => 'fail',
			'msg' => '操作失败',
		];
	}

	public function queryMenus(): array
	{
		$menus = PermissionModel::query()
			->where('type', 0)
			->orWhere('type', 1)
			->orderBy('sort')
			->get([
				'id',
				'pid',
				'name',
				'menu_icon',
				'request_uri',
			]);

		return $this->genTree($menus->toArray());
	}

	public function queryAll(): array
	{
		$permissions = PermissionModel::query()
			->whereNull('deleted_at')
			->orderBy('sort')
			->get([
				'id',
				'pid',
				'type',
				'authority',
				'name',
				'request_uri',
				'request_method',
				'menu_icon',
				'sort',
			]);

		foreach ($permissions as $permission) {
			$permission->request_uri = $permission->request_uri ?? '-';
		}

		return $permissions->toArray();
	}


	/**
	 * 树形结构生成
	 * @param $arr
	 * @param int $pid
	 * @param string $id
	 * @param string $pName
	 * @param string $child
	 * @return array
	 */
	protected function genTree($arr, $pid = 0, $id = 'id', $pName = 'pid', $child = 'child')
	{
		$tree = [];
		foreach ($arr as $value) {
			$value['title'] = $value['name'];
			$value['href'] = $value['request_uri'];
			$value['icon'] = $value['menu_icon'];
			$value['target'] = $value['_self'];
			unset($value['name']);
			unset($value['request_uri']);
			unset($value['menu_icon']);
			if ($value[$pName] == $pid) {
				$value[$child] = $this->genTree($arr, $value[$id], $id = 'id', $pName = 'pid', $child = 'child');
				if ($value[$child] == null) {
					unset($value[$child]);
				}
				$tree[] = $value;
			}
		}

		return $tree;
	}
}